﻿using JobManageCommon.Common;
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;

using System.Collections.Generic;
namespace JobManageCommon.Helper
{
    public class CmdHelper
    {  /// <summary>
       /// 执行cmd.exe命令
       /// </summary>
       /// <param name="commandText"></param>
       /// <returns></returns>
        public static string ExeCommand(string commandText, string Administrator, string version)
        {
            return ExeCommand(new string[] { commandText }, Administrator, version);
        }
        /// <summary>
        /// 执行多条cmd.exe命令
        /// </summary>
        /// <param name="commandTexts"></param>
        /// <returns></returns>
        public static string ExeCommand(string[] commandTexts, string Administrator, string version)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            string strOutput = null;
            var cmdstr = string.Format(@"cd C:\Users\{0}\AppData\Local\chia-blockchain\{1}\resources\app.asar.unpacked\daemon", Administrator, version);
            try
            {
                p.Start();

                p.StandardInput.WriteLine(@"start cmd /k  " + cmdstr);
                foreach (string item in commandTexts)
                {
                    p.StandardInput.WriteLine(@"start cmd /k cd C:\");
                }
                strOutput = p.StandardOutput.ReadToEnd();
                strOutput = Encoding.UTF8.GetString(Encoding.Default.GetBytes(strOutput));
                p.WaitForExit();
                p.Close();
            }
            catch (Exception e)
            {
                strOutput = e.Message;
            }
            return strOutput;
        }
        /// <summary>
        /// 启动外部Windows应用程序，隐藏程序界面
        /// </summary>
        /// <param name="appName">路径</param>
        /// <returns></returns>
        public static bool StartApp(string appName)
        {
            return StartApp(appName, ProcessWindowStyle.Hidden);
        }

        /// <summary>
        /// 启动外部应用程序
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="style"></param>
        /// <returns></returns>
        public static bool StartApp(string appName, ProcessWindowStyle style)
        {
            return StartApp(appName, null, style);
        }

        /// <summary>
        ///  启动外部应用程序，隐藏程序界面
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public static bool StartApp(string appName, string arguments)
        {
            return StartApp(appName, arguments, ProcessWindowStyle.Hidden);
        }

        /// <summary>
        ///  启动外部应用程序
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="arguments"></param>
        /// <param name="style"></param>
        /// <returns></returns>
        public static bool StartApp(string appName, string arguments, ProcessWindowStyle style)
        {
            bool blnRst = false;
            Process p = new Process();
            p.StartInfo.FileName = appName;//exe,bat and so on
            p.StartInfo.WindowStyle = style;
            p.StartInfo.Arguments = arguments;
            try
            {
                p.Start();
                p.WaitForExit();
                p.Close();
                blnRst = true;
            }
            catch
            {
            }
            return blnRst;
        }

        public static bool isok = false;

        /// <summary>
        ///  执行任务
        /// </summary>
        /// <returns></returns>
        public static bool OpenCmdStart(string batpath, string Administrator, string version, JobManageModel.Manage_JobModel.JobManageModel jobManageModel)
        {

            /// 每个SSD硬盘 应该做的任务数
            var spl = jobManageModel.DriveLetter.Count / jobManageModel.CacheDrive.Count;
            var splofexdrive = new List<string> { };
            var splofexSSDdrive = new List<string> { };
            int splindex = spl;
            if (jobManageModel.ModeType == 1)
            {
                int index = 1;
                foreach (var ssditem in jobManageModel.CacheDrive)
                {
                    foreach (var item in jobManageModel.DriveLetter)
                    {
                        if (!isok)
                        {
                            if (index > spl)
                            {
                                isok = true;
                                break;
                            }

                            splofexdrive.Add(item);
                            var htmlcmd = Forhtml(Administrator, version, jobManageModel.JobNum, ssditem, item, jobManageModel.Fingerprint, jobManageModel.FarmerKey, jobManageModel.PoolKey, int.Parse(jobManageModel.sjjiang),int.Parse(jobManageModel.KModel), int.Parse(jobManageModel.ThreadNum));

                            ExportCommon.Exportfun(batpath + @"\disc_0_" + index + ".bat", htmlcmd);
                            index++;
                            splindex--;
                        }
                        else
                        {
                            if (splofexdrive.Contains(item))
                            {
                                continue;
                            }
                            var htmlcmd = Forhtml(Administrator, version, jobManageModel.JobNum, ssditem, item, jobManageModel.Fingerprint, jobManageModel.FarmerKey, jobManageModel.PoolKey, int.Parse(jobManageModel.sjjiang), int.Parse(jobManageModel.KModel),int.Parse(jobManageModel.ThreadNum));

                            ExportCommon.Exportfun(batpath + @"\disc_0_" + index + ".bat", htmlcmd);
                            index++;
                            splindex--;
                        }
                    }
                }
                try
                {
                    isok = false;
                    index = 1;
                    foreach (var item in jobManageModel.DriveLetter)
                    {
                        var batindex = batpath + @"\disc_0_" + index + ".bat";
                        Process proc = Process.Start(batindex); ;
                        proc.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
                        index++;
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    ExportCommon.Exportfun(System.Environment.CurrentDirectory + "/error.log", ex.Message);
                    return false;
                }
            }
            else
            {
                int index = 1;
                foreach (var ssditem in jobManageModel.CacheDrive)
                {
                    foreach (var item in jobManageModel.DriveLetter)
                    {
                        if (!isok)
                        {
                            if (index > spl)
                            {
                                isok = true;
                                break;
                            }

                            splofexSSDdrive.Add(item);
                            var htmlcmd = Zuhehtml(Administrator, version, jobManageModel.JobNum, ssditem, item, jobManageModel.Fingerprint, jobManageModel.FarmerKey, jobManageModel.PoolKey,int.Parse(jobManageModel.sjjiang), int.Parse(jobManageModel.KModel), int.Parse(jobManageModel.ThreadNum));
                            ExportCommon.Exportfun(batpath + @"\disc_1_" + index + ".bat", htmlcmd);
                            index++;
                            splindex--;
                        }
                        else {
                            if (splofexSSDdrive.Contains(item)) {
                                continue;
                            }
                            var htmlcmd = Zuhehtml(Administrator, version, jobManageModel.JobNum, ssditem, item, jobManageModel.Fingerprint, jobManageModel.FarmerKey, jobManageModel.PoolKey,int.Parse(jobManageModel.sjjiang), int.Parse(jobManageModel.KModel), int.Parse(jobManageModel.ThreadNum));

                            ExportCommon.Exportfun(batpath + @"\disc_1_" + index + ".bat", htmlcmd);
                            index++;
                            splindex--;
                        } 
                    }
                }
                try
                {
                    index = 1;
                    isok = false;
                    foreach (var item in jobManageModel.DriveLetter)
                    {
                        var batindex = batpath + @"\disc_1_" + index + ".bat";

                        Process proc = Process.Start(batindex); ;
                        proc.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
                        index++;
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    ExportCommon.Exportfun(Environment.CurrentDirectory + "/error.log", ex.Message);
                    return false;
                }
            }
        }

        /// <summary>
        /// 密钥显示
        /// </summary>
        /// <param name="batpath"></param>
        /// <param name="Administrator"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public static string OpenCmdStarts(string batpath, string Administrator, string version)
        {
            try
            {
                var cmdstr = string.Format(@"
cd C:\Users\{0}\AppData\Local\chia-blockchain\app-{1}\resources\app.asar.unpacked\daemon
chia keys show
", Administrator, version);
                ExportCommon.Exportfun(batpath + @"\chiakeys.bat", cmdstr);
                Process proc = new Process();
                string dir = Environment.CurrentDirectory;
                proc.StartInfo.FileName = @"C:\Windows\system32\cmd.exe";
                proc.StartInfo.WorkingDirectory = dir;
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.RedirectStandardInput = false;
                proc.StartInfo.RedirectStandardOutput = false;
                proc.StartInfo.RedirectStandardError = false;
                proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                proc.StartInfo.CreateNoWindow = false;
                proc.StartInfo.Arguments = "/k " + batpath + @"\chiakeys.bat";
                proc.Start();
                return (cmdstr);
            }
            catch (Exception ex)
            {
                ExportCommon.Exportfun(System.Environment.CurrentDirectory + "/error.log", ex.Message);
                return ("error");
            }
        }
        public static string Zuhehtml(string Administrator, string version, int JobNum, string SSDDriveLetter, string DriveLetter, string Fingerprint, string FarmerKey, string PoolKey,int sjjg,int kmodel,int threadnum)
        {
            var cmdstr = string.Format(@"
cd C:\Users\{0}\AppData\Local\chia-blockchain\app-{1}\resources\app.asar.unpacked\daemon  
@echo off
for /l %%i in (1,1,{2}) do (   
start /min cmd /k chia plots create -k {9} -n {2} -t {3} -d {4} -b 4096 -u 128 -r {10} -a {5} -f {6}  -p {7} 
timeout {8} 
)

", Administrator, version, JobNum, SSDDriveLetter, DriveLetter, Fingerprint, FarmerKey, PoolKey, sjjg*60,kmodel,threadnum);
                        return cmdstr;
        }
        public static string Forhtml(string Administrator, string version, int JobNum, string SSDDriveLetter, string DriveLetter, string Fingerprint, string FarmerKey, string PoolKey,int sjjg, int kmodel,int threadnum)
        {
            var cmdstr = string.Format(@"
cd C:\Users\{0}\AppData\Local\chia-blockchain\app-{1}\resources\app.asar.unpacked\daemon  
@echo off
for /l %%i in (1,1,{2}) do (   
start /min cmd /k chia plots create -k {9} -n 1 -t {3} -d {4} -b 4096 -u 128 -r {10} -a {5} -f {6}  -p {7}
timeout {8} 
)
", Administrator, version, JobNum, SSDDriveLetter, DriveLetter, Fingerprint, FarmerKey, PoolKey,sjjg*60,kmodel,threadnum);
            return cmdstr;
        }
    }
}